import { Vec2, Vec3, loader } from "cc"

export function wxAvatar(avatarUrl: string, isCached: boolean = true) {
    if (isCached) {
        avatarUrl += `?carolsail.jpg`
    } else {
        const time = new Date().getTime()
        avatarUrl += `?carolsail=${time}.jpg`
    }
    return new Promise<void>((resolve, reject) => {
        loader.load(avatarUrl, function (err: any, texture: any) {
            if (err) reject && reject()
            resolve && resolve(texture)
        })
    })
}

export function uuid() {
    let d = new Date().getTime();
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

export function getDis(from: Vec2 | Vec3, to: Vec2 | Vec3) {
    const x = from.x - to.x
    const y = from.y - to.y
    const distance = Math.sqrt(x * x + y * y)
    return distance
}

export function getRand(lower: number, upper: number) {
    return Math.floor(Math.random() * (upper - lower + 1)) + lower
}

export function formatTimer(seconds: number | string, format = 'h:i:s'): string {
    seconds = Number(seconds)
    let data: any = {}
    data.h = Number.parseInt(String(seconds / 3600));
    data.i = Number.parseInt(String((seconds - data.h * 3600) / 60));
    data.s = Number.parseInt(String(seconds - data.h * 3600 - data.i * 60));
    if (data.h < 10) data.h = '0' + data.h;
    if (data.i < 10) data.i = '0' + data.i;
    if (data.s < 10) data.s = '0' + data.s;
    let str = format.replace('h', data.h).replace('i', data.i).replace('s', data.s);
    return str;
}